package com.cindata

import grails.transaction.Transactional
import org.springframework.security.access.annotation.Secured

import com.cindata.dictionary.WorkflowType

@Secured(['isAuthenticated()'])
@Transactional
class FlowStageController
{

    def dataSource

    def flowStageIndex()
    {
        def max = Math.min(params.max ? params.max.toInteger() : 10, 100)
        def offset = params.offset ? params.offset.toInteger() : 0

        def db = new groovy.sql.Sql(dataSource)

        def code = params['code']
        def name = params['name']
        def className = params['class']

        def sql = "select id, name, code, class, type_id from flow_stage where 1=1"
        if (name)
        {
            sql += " and name like '%${name}%'"
        }
        if (code)
        {
            sql += " and code like '%${code}%'"
        }
        if (className)
        {
            sql += " and class like '%${className}%'"
        }

        sql += " order by code desc"
        def result = db.rows(sql, offset + 1, max).asList()
        def resultList = db.rows(sql).asList()

        respond result, model: [result: result, counts: resultList?.size()]
    }

    def flowStageShow(FlowStage flowStage)
    {
        respond flowStage, model: [flowStage: flowStage]
    }

    def flowStageEdit(FlowStage flowStage)
    {
        respond flowStage, model: [flowStage: flowStage]
    }

    def flowStageUpdate(FlowStage flowStage)
    {
        flowStage.save flush: true
        redirect action: 'flowStageShow', id: flowStage?.id, params: [class: params?.class, title: params?.title]
    }

    def flowStageCreate()
    {
    }

    @Transactional
    def flowStageSave()
    {
        def className = params['class']
        def name = params['name']
        def code = params['code']
        def type = params['type']

        Class object = Class.forName("com.cindata.dictionary.${className}")
        def flowStage = object.newInstance()

        flowStage.code = code
        flowStage.name = name
        flowStage.type = WorkflowType.findById(type)
        if (flowStage.validate()) 
        {
            flowStage.save flush: true    
        }
        else
        {
            println flowStage.errors
        }

        redirect action: 'flowStageIndex', params: [class: params?.class, title: params?.title]
    }
}
